package org.luckystrophe.snowtoms.manager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import org.luckystrophe.snowtoms.model.JsonRequest;

import com.googlecode.androidannotations.annotations.EBean;
import com.googlecode.androidannotations.api.Scope;

@EBean(scope = Scope.Singleton)
public class HttpConnectManager {

	private static InputStream inputStream = null;

	public static JSONObject getConnection(JsonRequest request) throws JSONException, ClientProtocolException,
			IOException {
		JSONObject result = new JSONObject();
		HttpUriRequest httpRequest = request.getHttpUriRequest();
		HttpParams params = new BasicHttpParams();
		params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		httpRequest.setParams(params);

		HttpClient httpClient = new DefaultHttpClient();

		HttpResponse response = httpClient.execute(httpRequest);
		HttpEntity entityResponse = response.getEntity();

		inputStream = entityResponse.getContent();

		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
			sb.append(line).append("\n");
		}
		inputStream.close();
		result = new JSONObject(sb.toString());
		return result;
	}
}
